
import asyncio
import time
from multiprocessing import Queue
from sqlalchemy import text, select, and_, or_, func
from sqlalchemy.ext.asyncio import AsyncSession
from initialization.crudInit import delete_pojo_by_relation
from initialization.dbInit import get_async_session
from initialization.redisInit import get_sync_redis
from model.entitys import User, Menu, RoleMenu, UserRole
from requestProcessing.httpRequest import HttpRequest
from service import logger
from variable import dependent_data

def my_job():
    t = 0
    while True:
        print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

        if t == 1000:
            raise "报错。。。。。。。。。。。。"

        time.sleep(2)

def handle_task():
    logger.debug(repr("testing Scheduled Task"))

    # dependent_data["thread_sched"].add_job(my_job, 'interval', seconds=5)
    dependent_data["ground_sched"].add_job(my_job, 'interval', seconds=5)

def add_sched_test():
    handle_task()

    # session = await get_async_session()
    #
    # await delete_pojo_by_relation(session, User, 'f9675d76-7909-11ec-980c-1c697ac9cfe3', UserRole, "userId")
    # await session.commit()
    #
    # data = (await session.execute(text("select m.* from menu m \
    #                                     inner join role_menu rm on rm.menuId = m.id \
    #                                     inner join user_role ur on ur.roleId = rm.roleId \
    #                                     where ur.userId in (select u.id from `user` u \
    #                                            where (u.username = :username1 \
    #                                            or u.username = :username2) and u.nickname = :nickname)"),
    #                               params={"username1": "Harden", "username2": "admin",
    #                                       "nickname": "Harden"})).fetchall()
    #
    # sub_query = (select(User.id).where(or_(User.username == 'admin', User.username == 'Harden')).where(
    #     and_(User.nickname == 'Harden')).scalar_subquery())
    #
    # # data = (await session.execute(select(Menu).join(RoleMenu, RoleMenu.menuId == Menu.id). \
    # #                               join(UserRole, UserRole.roleId == RoleMenu.roleId). \
    # #                               where(UserRole.userId.in_(sub_query)))).scalars().all()
    #
    # total = (await session.execute(select(func.count(Menu.id)).join(RoleMenu, RoleMenu.menuId == Menu.id). \
    #                               join(UserRole, UserRole.roleId == RoleMenu.roleId). \
    #                               where(UserRole.userId.in_(sub_query)))).first()[0]
    #
    # await session.close()

    return {"message": "添加成功", "code": 200, "data": None, "total": 0}

async def add(session: AsyncSession):
    await session.execute(text("insert into `user` values(uuid(), '美猴王', 'sunwukong', 'huaguoshan', '异步添加 用户', now(), now())"))
    await session.commit()
    await session.close()

async def delete(session: AsyncSession, user_id: str):
    await session.execute(text("delete from `user` where id = :user_id"), params={"user_id": user_id})
    await session.commit()
    await session.close()

async def update(session: AsyncSession, user_id: str):
    await session.execute(text("update `user` set username = '异步修改 用户' where id = :user_id"),
                          params={"user_id": user_id})
    await session.commit()
    await session.close()

async def t_func(n):
    for i in range(n):
        print("走啊。。。。。。。。。。。。。。。。。。。。。。。。。。。", i)
        await asyncio.sleep(2)

async def add_async(n):
    session = await get_async_session()

    for i in range(n):
        await session.execute(
            text("insert into `user` values(uuid(), '美猴王', 'sunwukong', 'huaguoshan', '异步添加 用户', now(), now())"))
        await session.commit()

        await asyncio.sleep(2)

    await session.close()

def blend(count):
    # session = await get_async_session()
    # await asyncio.sleep(1)

    hr = HttpRequest()
    queue = Queue()
    for user in range(count):
        # await asyncio.sleep(1)

        resp = hr.request("get", 'https://dev.tiktok.api.vodeshop.com/api/v1/qiniu-upload-token', header={
            "authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvZGV2LnRpa3Rvay5hcGkudm9kZXNob3AuY29tXC9hcGlcL3YxXC9hdXRoXC9sb2dpblwvc21zIiwiaWF0IjoxNjQ5NzYzNDc5LCJleHAiOjE3MDk3NjM0NzksIm5iZiI6MTY0OTc2MzQ3OSwianRpIjoiVjFPbDR6c3ZRZUtqbE43TSIsInN1YiI6MzIsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjcifQ.KIYZKZjPk7YZzO3bJKC7ij10YN7Am-FrlMbry-vHw2c"},
                          param_type=None,
                             ).json()
        print(resp)

        file2 = {"file": open('E:/be046956-7b49-4d27-97e6-eb8bb5d8b22f.jpg', "rb")}
        resp1 = hr.request("post", 'https://upload-z2.qiniup.com', header={
            "authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvZGV2LnRpa3Rvay5hcGkudm9kZXNob3AuY29tXC9hcGlcL3YxXC9hdXRoXC9sb2dpblwvc21zIiwiaWF0IjoxNjQ5NzYzNDc5LCJleHAiOjE3MDk3NjM0NzksIm5iZiI6MTY0OTc2MzQ3OSwianRpIjoiVjFPbDR6c3ZRZUtqbE43TSIsInN1YiI6MzIsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjcifQ.KIYZKZjPk7YZzO3bJKC7ij10YN7Am-FrlMbry-vHw2c",
            },
            param_type="form",
            params={"token": resp["data"]["uptoken"]}, file_list=file2).json()

        print("执行函数：", blend)

        time.sleep(30)

def async_test():
    # session1 = await get_async_session()
    # session2 = await get_async_session()
    # session3 = await get_async_session()
    #
    # asyncio.create_task(add(session1))
    # asyncio.create_task(delete(session2, 'cc9affae-7dbd-11ec-8902-1c697ac9cfe3'))
    # asyncio.create_task(update(session3, '253c1afa-7db0-11ec-8d74-1c697ac9cfe3'))

    # asyncio.create_task(t_func(100))
    # asyncio.create_task(add_async(100))

    # sync_redis = get_sync_redis()
    # v = sync_redis.get("async_redis")
    # print("sync_redis     redis同步取key：", v)

    # print("Thread。。。。。。。。。。。。。。。。。。。。。。。。。。。。", )
    for i in range(3):
        # asyncio.create_task(blend(5))
        blend(5)

    # return {"message": "操作成功", "code": 200, "data": None}















































